package com.ruoyi.grc.utils;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.grc.domain.T01Seq;
import com.ruoyi.grc.service.IT01SeqService;

import java.util.Date;
import java.util.List;

public class SeqUtils {
    public static String getNextCode(String code) {
        IT01SeqService seqService = SpringUtils.getBean(IT01SeqService.class);

        T01Seq t01Seq = new T01Seq();
        t01Seq.setCode(code);

        List<T01Seq> t01Seqs = seqService.selectT01SeqList(t01Seq);
        if(t01Seqs.size()>0){
            t01Seq=t01Seqs.get(0);
            return getNextCodeBySeq(t01Seq, seqService);

        }
        return null;
    }

    public static String getNextCodeBySeq(T01Seq t01Seq ,IT01SeqService seqService ){
        Date lastTime = t01Seq.getLastTime();
        Date nowDate = DateUtils.getNowDate();
        Date userDate = null;
        long between = DateUtil.between(lastTime, nowDate, DateUnit.DAY);
        T01Seq t01SeqUpdate = new T01Seq();
        t01SeqUpdate.setId(t01Seq.getId());
        Long seqIndex=1l;
        if(between==0){ //同一天
            userDate=lastTime;  //时间选择
            seqIndex = t01Seq.getSeqIndex() +1; // 序号选择

            t01SeqUpdate.setSeqIndex(seqIndex); // 更新序号


            t01SeqUpdate.setPreSeqIndex(t01Seq.getSeqIndex());  //更新条件 + 上个序号

        }else {
            userDate=nowDate;  //时间选择
            seqIndex=1l;   // 序号选择

            t01SeqUpdate.setSeqIndex(seqIndex); // 更新序号
            t01SeqUpdate.setLastTime(userDate);    // 更新时间


            t01SeqUpdate.setPreLastTime(lastTime);   //更新条件 + 上个序号

        }
        int i = seqService.updateT01Seq(t01SeqUpdate);

        if(i>0){
            String template = "{}{}{}";
            return StrUtil.format(template
                    ,t01Seq.getPrefix()
                    ,DateUtil.format(userDate,"yyyyMMdd")
                    ,addPrefex(seqIndex)
            );
        }
        return null;
    }

    public static String addPrefex(Long c ) {
       return addPrefex(c,4,"0");
    }

    public static String addPrefex(Long c ,int maxLength ,String prefex) {
        String format = NumberUtil.toStr(c);//299,792,458
        StringBuilder stringBuilder = new StringBuilder();
        if(format.length()< maxLength){
            int length = format.length();
            int count = ( maxLength-length);
            for (int i = 0; i < count ; i++) {
                stringBuilder.append(prefex);
            }

        }

       return stringBuilder.append(format).toString();
    }

}
